package com.znxs.zuopao_c.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.znxs.zuopao_c.common.ErrorCode;
import com.znxs.zuopao_c.domain.User;
import com.znxs.zuopao_c.exception.BusinessException;
import com.znxs.zuopao_c.mapper.UserMapper;
import com.znxs.zuopao_c.service.UserService;
import com.znxs.zuopao_c.utils.AlgorithmUtils;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.znxs.zuopao_c.contant.userContant.ADMIN_ROLE;
import static com.znxs.zuopao_c.contant.userContant.USER_LOGIN_STATE;

/**
 * @author znxs
 * &#064;createTime  2023-08-30 15:19:35
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;


    public static final String SALT = "znxs";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String plantCode) {
        // 非空校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, plantCode)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户不长度小于4位");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度小于8位");
        }
        if (plantCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号大于5位");
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户不能包含特殊字符");
        }
        // 密码和校验密码需要相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码和校验密码需要相同");
        }
        // 账户不能重复  [这里查询数据库，如果能放到后面就放到后面，减少资源调用]
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_account", userAccount);
        Long one = userMapper.selectCount(userQueryWrapper);
        if (one > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户不能重复");
        }
        // 星球编号不能重复
        userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("plant_code", plantCode);
        Long count = userMapper.selectCount(userQueryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号不能重复");
        }
        // 密码加密
        final String SALT = "znxs";
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlantCode(plantCode);
        boolean reusltSave = this.save(user);
        if (!reusltSave) return -1;
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 非空校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            // todo 等会添加成自定义异常
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户不能重复");
        }
        // 密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_account", userAccount);
        userQueryWrapper.eq("user_password", encryptPassword);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null) {
            log.info("user login failed ,userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        // 脱敏
        User safetyUser = getSafetyUser(user);
        // 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }


    @Override
    public User getSafetyUser(User oldUser) {
        if (oldUser == null) return null;
        User safetyUser = new User();
        safetyUser.setId(oldUser.getId());
        safetyUser.setUsername(oldUser.getUsername());
        safetyUser.setUserAccount(oldUser.getUserAccount());
        safetyUser.setAvatarUrl(oldUser.getAvatarUrl());
        safetyUser.setGender(oldUser.getGender());
        safetyUser.setPhone(oldUser.getPhone());
        safetyUser.setEmail(oldUser.getEmail());
        safetyUser.setUserStatus(oldUser.getUserStatus());
        safetyUser.setCreateTime(oldUser.getCreateTime());
        safetyUser.setUserRole(oldUser.getUserRole());
        safetyUser.setPlantCode(oldUser.getPlantCode());
        safetyUser.setTags(oldUser.getTags());
        safetyUser.setProfile(oldUser.getProfile());
        return safetyUser;
    }

    @Override
    public void outLogin(HttpServletRequest request) {
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
    }


    @Override
    public List<User> searchUserByTags(List<String> tagNamesList) {
        // 是否为空
        if (CollectionUtils.isEmpty(tagNamesList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        // 创建查询 拼接
        for (String tagName : tagNamesList) {
            userQueryWrapper = userQueryWrapper.like("tags", tagName);
        }
        // 查询数据
        List<User> userList = userMapper.selectList(userQueryWrapper);
        if (CollectionUtils.isEmpty(userList)) {
            return null;
        }
        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());
    }


    @Override
    public Boolean updateUser(User user, User userLogin) {
        // 判断用户权限 仅管理员和自己可以修改
        Long userId = user.getId();
        if (userId < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 如果是管理员 就可以修改所有人的数据
        // 如果不是管理员 就修改自己的数据
        if (!isAdmin(userLogin) && !Objects.equals(userLogin.getId(), userId)) {
            throw new BusinessException(ErrorCode.NO_AUTH,"无权限修改");
        }
        User oldUser = userMapper.selectById(userId);
        if (oldUser == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"用户不存在");
        }
        return this.updateById(user);
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        Object LoginUser = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (LoginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        return (User) LoginUser;
    }

    @Override
    public User isLogin(HttpServletRequest request){
        if (request == null) {
            throw new BusinessException(ErrorCode.SYS_ERROR);
        }
        Object LoginUser = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (LoginUser==null) return null;
        return (User)LoginUser;
    }

    @Override
    public List<User> searchUserByTagsBefore(List<String> tagNamesList) {
        // 是否为空
        if (CollectionUtils.isEmpty(tagNamesList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        // 查询数据
        List<User> userList = userMapper.selectList(userQueryWrapper);
        Gson gson = new Gson();
        // 使用内存的方式
        return userList.stream().filter(user -> {
            String tagsStr = user.getTags();
            // 把数据库中的json字符串转成对象
            Set<String> tempTagNameSet = gson.fromJson(tagsStr, new TypeToken<Set<String>>() {
            }.getType());
            // 通过ofNullable 判断是否为空 如果为空就给这个复制一个默认值
            tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());
            for (String tagName : tagNamesList) {
                if (!tempTagNameSet.contains(tagName)) {
                    return false;
                }
            }
            return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());
    }

    @Override
    public List<User> matchUsers(long num, User loginUser) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "tags");
        queryWrapper.isNotNull("tags");
        List<User> userList = this.list(queryWrapper);
        String tags = loginUser.getTags();
        Gson gson = new Gson();
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {
        }.getType());
        // 用户列表的下标 => 相似度
        List<Pair<User, Long>> list = new ArrayList<>();
        // 依次计算所有用户和当前用户的相似度
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            String userTags = user.getTags();
            // 无标签或者为当前用户自己
            if (StringUtils.isBlank(userTags) || Objects.equals(user.getId(), loginUser.getId())) {
                continue;
            }
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {
            }.getType());
            // 计算分数
            long distance = AlgorithmUtils.minDistance(tagList, userTagList);
            list.add(new Pair<>(user, distance));
        }
        // 按编辑距离由小到大排序
        List<Pair<User, Long>> topUserPairList = list.stream()
                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                .limit(num)
                .collect(Collectors.toList());
        // 原本顺序的 userId 列表
        List<Long> userIdList = topUserPairList.stream().map(pair -> pair.getKey().getId()).collect(Collectors.toList());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", userIdList);
        // 1, 3, 2
        // User1、User2、User3
        // 1 => User1, 2 => User2, 3 => User3
        Map<Long, List<User>> userIdUserListMap = this.list(userQueryWrapper)
                .stream()
                .map(user -> getSafetyUser(user))
                .collect(Collectors.groupingBy(User::getId));
        List<User> finalUserList = new ArrayList<>();
        for (Long userId : userIdList) {
            finalUserList.add(userIdUserListMap.get(userId).get(0));
        }
        return finalUserList;
    }


    @Override
    public <T> boolean doCache(String redisKey , T cacheData) {
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 查看是否有数据
        T data  = (T)valueOperations.get(redisKey);
        if (data!=null){
            return false;
        }
        // 然后写入redis中
        try {
            valueOperations.set(redisKey,cacheData,100000, TimeUnit.MILLISECONDS);
            return true;
        } catch (Exception e) {
            // 这里如果写缓存失败了，也不用直接抛异常 需要返回值到前端
            log.error("redis setKey error",e);
            return false;
        }
    }

    public Boolean isAdmin(HttpServletRequest request) {
        // 获取登录态
        User userObj = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        // 鉴权 （不是管理员就静止调用）
        return userObj != null && userObj.getUserRole() == ADMIN_ROLE;
    }

    public Boolean isAdmin(User userLogin) {
        // 鉴权 （不是管理员就静止调用）
        return userLogin != null && userLogin.getUserRole() == ADMIN_ROLE;
    }



}






